import {
  OnInit,
  OnChanges,
  OnDestroy,
  Component,
  ChangeDetectionStrategy,
  ViewEncapsulation,
  Input,
  TemplateRef,
  NgZone,
  ViewChild,
  ElementRef,
} from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Lbchart } from '@shared';
import { Subscription } from 'rxjs';
import { SupData } from '@core/lb/SupData';
/**
 * 基础饼图
 */
@Component({
  selector: 'lb-basic-pie',
  template: `
    <div #basicpie></div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbBasicPieComponent
  implements OnInit, OnChanges, OnDestroy, Lbchart {
  private chart: any;
  private resize$: Subscription;

  @ViewChild('basicpie', { static: true }) private node: ElementRef;
  @Input() @InputNumber() delay = 0;
  @Input() position: any;
  @Input() height: number;
  @Input() data: any[];


  // 以下输入均为样式
  @Input() color: string[] = null;
  @Input() colorFiled = 'name';
  @Input() padding: Array<number | string> | string = 'auto';

  @Input() radius1: number;
  @Input() radius0: number;

  @Input() @InputBoolean() centertitleshow = false; // 是否显示内部标题
  @Input() centertitletext; // 内部标题
  @Input() @InputNumber() centertitletextsize
  @Input() @InputBoolean() centertitleshowtotal = false;
  @Input() @InputNumber() centertitletotalsize

  @Input() @InputBoolean() tooltipshow = true;
  @Input() @InputBoolean() tooltipshowpercent = true;
  @Input() @InputBoolean() tooltipshowtitle = false

  @Input() legendposition;
  @Input() legendlayout;
  @Input() @InputBoolean() legendshow = true;
  @Input() @InputBoolean() legendshowpercent = true;
  @Input() @InputBoolean() legendshowdata = false;

  @Input() @InputBoolean() labelshow = false;

  @Input() sortx = true
  @Input() sortz
  @Input() sortrule = 'ASC'

  constructor(private ngZone: NgZone, private supdata: SupData) {}

  commonStyleHandle(chart, data) {
    // 计算百分比
    console.log('lb-basic-pie: ')
    console.log(this.position)
    console.log(data)
    const dv = new DataSet.View().source(data);
    // if(this.sortx && !this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,        // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(!this.sortx && this.sortz){
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(this.sortx && this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx, this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // }    
    dv.transform({
      type: 'percent',
      field: this.position.y, // 统计销量
      dimension: this.position.x, // 每年的占比
      // groupBy: [ 'category' ], // 以不同产品类别为分组，每个分组内部各自统计占比
      as: 'percent', // 结果存储在 percent 字段
    });

    // Step 2: 载入数据源
    chart.source(dv.rows, {
      percent: {
        formatter: val => {
          val = val * 100 + '%';
          return val;
        },
      },
    });

    // 工具提示
    if (this.tooltipshow) {
      chart.tooltip({
        showTitle: this.tooltipshowtitle,
        itemTpl: '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}'+ (this.tooltipshowpercent? '({percent}%)': '') +'</li>'
      });
    } else {
      chart.tooltip(false);
    }

    // 图例
    if (this.legendshow) {
      chart.legend(this.position.x, {
        position: this.legendposition,
        layout: this.legendlayout,
        itemFormatter: val => {
          return (
            val.toString() +
            (this.legendshowpercent
              ? '    (' +
                Math.round(
                  dv.rows.find(ele => ele[this.position.x] === val).percent *
                    10000,
                ) /
                  100 +
                '%)'
              : '')+(this.legendshowdata? "    "+dv.rows.find(ele => ele[this.position.x] === val)[this.position.y]:'')
          );
        },
      });
    } else {
      chart.legend(false);
    }

    // 饼图半径
    chart.coord('theta', {
      radius: this.radius1 ? this.radius1 / 100 : 1,
      innerRadius: this.radius0 ? this.radius0 / 100 : 0,
    });

    return dv.rows;
  }

  rChartHandle(geom) {
    if (this.labelshow) {
      geom.label(this.position.x, x => {
        if (!this.labelshow) return null;
        return {
          offset: 10,
          textStyle: {
            // fill: 'white',
            fontSize: 12,
            shadowBlur: 2,
          },
          rotate: 0,
          autoRotate: false,
        };
      });
    } else {
      // geom.label(false)
    }
  }

  install(resdata) {
    // 图表信息
    const dataFilds: string[] = resdata.message.tb.DAA035.split(',');
    const groupFileds: string[] = resdata.message.tb.DAA036.split(',');
    // 字段信息

    // 数据处理
    let data = this.supdata.rebuildData(
      resdata.message.data,
      resdata.message.tb,
      groupFileds,
      groupFileds,
    );
    // 字典转化
    data = this.supdata.rebuildDsDataToLabel(data);

    this.data = data;
    this.position = { x: groupFileds[0], y: dataFilds[0] };
    // this.radius0 = 0.5;

    this.render();
  }

  render() {
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true, // 图表的宽度自适应开关
      height: this.getHeight(),
      padding,
    }));

    this.commonStyleHandle(chart, this.data);
    const geom = chart
      .intervalStack()
      .position(`${this.position.y}`)
      .color(`${this.position.x}`)
      .tooltip(
        `${this.position.x}*${this.position.y}*percent`,
        (x, y, percent) => {
          return {
            name: x,
            value: y,
            percent: Math.round(percent * 10000) / 100,
          };
        },
      );

    this.rChartHandle(geom);

    let total = 0;
    this.data.forEach(ele => {
      total += ele[this.position.y];
    });

    // 中心标题
    chart.guide().html({
      // position: [ '50%', '50%' ],
      position: (xScale, yScale) => {
        return this.centertitleshow ? ['50%', '50%'] : null;
      },
      // html: '<div style="color:#8c8c8c;font-size: 14px;text-align: center;width: 10em;">'+this.centertitletext+'<br><span style="color:#8c8c8c;font-size:20px">200</span></div>',
      html: val => {
        return (
          `<div style="color:#8c8c8c;font-size: ${this.centertitletextsize}px;text-align: center;width: 10em;">${this.centertitletext}<br><span style="color:#8c8c8c;font-size:${this.centertitletotalsize}px">${this.centertitleshowtotal ? total : ''}</span></div>`
        )
      },
      alignX: 'middle',
      alignY: 'middle',
    });

    // Step 4: 渲染图表
    chart.render();
  }

  
  attachChart() {
    const { radius1, radius0 } = this;
    const { chart, padding, data, color } = this;
    if (!chart || !data || data.length <= 0) return;
    const dvrows = this.commonStyleHandle(chart, this.data);

    const height = this.getHeight();
    if (chart.get('height') !== height) {
      chart.changeHeight(height);
    }

    chart.set('padding', padding);
    chart.changeData(dvrows);
  }

  destroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
  getHeight() {
    return this.height;
    // return this.title ? (this.height - TITLE_HEIGHT) : this.height;
  }

  ngOnInit(): void {
    if (this.position && this.data !== undefined) {
      this.ngZone.runOutsideAngular(() =>
        setTimeout(() => this.render(), this.delay),
      );
    }
  }

  ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.attachChart());
  }
  ngOnDestroy(): void {
    this.destroy();
  }
}
